package com.df.base.updater;

import com.df.base.common.IScript;
import com.df.base.other.SpringContextHelper;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
public abstract class AbstractGroovyUpdater implements IGroovyUpdater{
    protected boolean firsetUpdate = true;

    private Thread task;

    @PostConstruct
    public void startTask(){
        task = new Thread(()->{
            long delay = GroovyUpdateContext.delay;
            long interval = GroovyUpdateContext.interval;
            if(delay>0){
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    return;
                }
            }
            while (true){
                try {
                    this.update();
                }catch (Exception e){
                    e.printStackTrace();
                }
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    return;
                }
            }
        });
        task.setName(this.getClass().getSimpleName());
        task.start();
    }
    @Override
    public abstract void update();


    protected void autowireScripts(IScript script){
        SpringContextHelper.getContext().getAutowireCapableBeanFactory().autowireBean(script);
    }

    @PreDestroy
    public void stopTask(){
        if(task!=null && task.isAlive()){
            log.info(this.getClass().getSimpleName()+" 线程停止");
            task.interrupt();
        }
    }
}
